//
//  AddCity.m
//  UIA段项目 墨家天气
//
//  Created by dllo on 15/8/20.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "AddCity.h"
#import "AddCityLayout.h"
#import "URL.h"
#import "GDataXMLNode.h"
#import "WeatherViewController.h"
#import "MyCollectionCell.h"
#import "ChoseViewController.h"
#import "BackTo.h"
#import "AddCityCell.h"
#import "NovelDataBase.h"
#import "NovelModel.h"
#import "Reachability.h"
#import "URL.h"
#import "UIImageView+WebCache.h"
#define columns 2
#define rows 3
#define itemsPerPage 15
#define space 20
#define gridHight 100
#define gridWith 100
#define unValidIndex  -1
#define threshold 30



@interface AddCity ()<UICollectionViewDataSource,UICollectionViewDelegate,ChoseViewControllerDelegate,UIAlertViewDelegate>

-(NSInteger)indexOfLocation:(CGPoint)location;
-(CGPoint)orginPointOfIndex:(NSInteger)index;
-(void) exchangeItem:(NSInteger)oldIndex withposition:(NSInteger) newIndex;


@property (nonatomic,retain)NSMutableArray *arr;
@property (nonatomic,retain)UIView *headerView;
@property (nonatomic,retain)UICollectionView *collect;
@property (nonatomic,retain)UIActivityIndicatorView *acticity;
@property (nonatomic,retain)NSArray *dataArr;
@property (nonatomic,assign)CGFloat b;
@property (nonatomic,assign)NSInteger items;
@property (nonatomic,retain)UILabel *defultLable;
@property (nonatomic,copy)NSString *backGound;
@property (nonatomic,retain)NSMutableDictionary *dataDic;
@property (nonatomic,retain)UILabel *hint;
@end

@implementation AddCity
@synthesize background;
@synthesize scroll;
int a = 0;
int item = 0;
-(void)dealloc
{
    [_model release];
    [_acticity release];
    [_headerView release];
    [_dataArr release];
    [_arr release];
    [_dic release];
    [_cityId release];
    [_cityName release];
    [_backImage release];
    [_inserArr release];
    [_reciveArr release];
    [_collect release];
    [_defultLable release];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"fff" object:@"f"];
    [super dealloc];

    
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.model = [[BackTo alloc]init];
        [_model release];
        
        self.reciveArr = [NovelDataBase selectAll];
        self.dataArr = [NSArray array];
        
        self.defultLable = [[UILabel alloc]init];
        [_defultLable release];
        self.hint = [[UILabel alloc]init];
        self.hint.frame = CGRectMake((self.view.frame.size.width - 50) / 2, self.view.frame.size.height - 100, 100, 30);
        self.hint.text = @"长按城市卡片,可删除城市";
        [_hint release];
        self.dataDic = [NSMutableDictionary dictionary];
        [self aaaaaaaa];
    }
    
    return self;
   
}
- (void)ggg
{
    CGRect frame = CGRectMake(20, 20, 100, 100);
    int n = [gridItems count];
    int row = (n-1) / 3;
    int col = (n-1) % 3;
    int curpage = (n-1) / itemsPerPage;
    row = row % 4;
    if (n / 10 + 1 > 10) {
        NSLog(@"不能创建更多页面");
    }else{
        
        
        for ( int i = 0; i < self.dataArr.count; i ++) {
                        if ([[[[self.dataArr objectAtIndex:i] objectForKey:@"type"] stringValue] isEqualToString:@"200" ]) {
            
                            self.dataDic = [[self.dataArr objectAtIndex:i] objectForKey:@"future"];
            
                        }
                    }
        
    
        

        
        
        frame.origin.x = frame.origin.x + frame.size.width * col + 20 * col + scroll.frame.size.width * curpage;
        frame.origin.y = frame.origin.y + frame.size.height * row + 20 * row;
   
        BJGridItem *gridItem = [[BJGridItem alloc]initWithName:self.cityName withHigh:[[[self.dataDic objectForKey:@"temp"] objectForKey:@"height"]stringValue] low:[[[self.dataDic objectForKey:@"temp"] objectForKey:@"low"]stringValue] wind:[[[[self.dataDic objectForKey:@"items"] objectAtIndex:1] objectForKey:@"climate"] objectForKey:@"name"] atIndex:n - 1 editable:YES];
                                
                                
                                
                                
                                
        [gridItem setFrame:frame];
        gridItem.backgroundColor = [[ UIColor blackColor]colorWithAlphaComponent:0.5];

        gridItem.delegate = self;
        [gridItems insertObject:gridItem atIndex:n-1];
        [scroll addSubview:gridItem];
        gridItem = nil;
        
        //move the add button
        row = n / 3;
        col = n % 3;
        curpage = n / 20;
        row = row % 10;
        frame = CGRectMake(20, 20, 100, 100);
        frame.origin.x = frame.origin.x + frame.size.width * col + 20 * col + scroll.frame.size.width * curpage;
        frame.origin.y = frame.origin.y + frame.size.height * row + 20 * row;
        NSLog(@"add button col:%d,row:%d,page:%d",col,row,curpage);
        [scroll setContentSize:CGSizeMake(scroll.frame.size.width * (curpage + 1), scroll.frame.size.height)];
        [scroll scrollRectToVisible:CGRectMake(scroll.frame.size.width * curpage, scroll.frame.origin.y, scroll.frame.size.width, scroll.frame.size.height) animated:NO];
        [UIView animateWithDuration:0.2f animations:^{
            [addbutton setFrame:frame];
        }];
        addbutton.index += 1;
        
        
        
    
        
        NovelModel *model1 = [[NovelModel alloc]init];
        
        model1.cityId = self.cityId;
        model1.cityName = self.cityName;
        model1.backImage = self.backImage;
        model1.high = [[[self.dataDic objectForKey:@"temp"] objectForKey:@"height"]stringValue];
        model1.low =  [[[self.dataDic objectForKey:@"temp"] objectForKey:@"low"]stringValue];
        model1.sky =  [[[self.dataDic objectForKey:@"items"] objectAtIndex:1] objectForKey:@"climate"];
        [NovelDataBase insertWithModel:model1];
                       
                       
                       
                       
                       
                       
        
    }
    
    

}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self addCollectionView];
    [self addHeaderView];
    
    
    
    page = 0;
    isEditing = NO;
//    addbutton = [[BJGridItem alloc] initWithTitle:@"Add" withImageName:nil atIndex:0 editable:NO];
    addbutton = [[BJGridItem alloc]initWithName:@"Add" withHigh:nil low:nil wind:nil atIndex:0 editable:NO];
    [addbutton setFrame:CGRectMake(0, 0, 100, 120)];
    addbutton.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
    addbutton.delegate = self;
    
    
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
    
    
    [self.view addSubview:self.scroll];
    [self.scroll addSubview: addbutton];

    
    
    gridItems = [[NSMutableArray alloc] initWithCapacity:15];
    [gridItems addObject:addbutton];
    self.scroll.delegate = self;
    [self.scroll setPagingEnabled:YES];
    singletap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singletap setNumberOfTapsRequired:1];
    singletap.delegate = self;
    [self.scroll addGestureRecognizer:singletap];

    
    
    
    
    
}
- (void)aaaaaaaa
{
    for (int i = 0; i < self.reciveArr.count; i ++) {
        
        
        
        CGRect frame = CGRectMake(20, 20, 100, 100);
        int n = [gridItems count];
        int row = (n-1) / 3;
        int col = (n-1) % 3;
        int curpage = (n-1) / itemsPerPage;
        row = row % 4;
        if (n / 10 + 1 > 10) {
            NSLog(@"不能创建更多页面");
        }else{
            
            
            
            if (i  < self.reciveArr.count) {
                
                NovelModel *model = [self.reciveArr objectAtIndex:i];
                
                
                //                cell.high.text = model.high;
                //                cell.low.text = model.low;
                self.cityName = model.cityName;
                //                cell.sky.text = model.sky;
                
                a =  0;

            
            frame.origin.x = frame.origin.x + frame.size.width * col + 20 * col + scroll.frame.size.width * curpage;
            frame.origin.y = frame.origin.y + frame.size.height * row + 20 * row;
            

                
            BJGridItem *gridItem = [[BJGridItem alloc] initWithName:self.cityName withHigh:model.high  low:model.low wind:model.wind atIndex:n - 1 editable:YES];
            [gridItem setFrame:frame];
                gridItem.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
            gridItem.delegate = self;
            [gridItems insertObject:gridItem atIndex:n-1];
            [scroll addSubview:gridItem];
            gridItem = nil;
            
            //move the add button
            row = n / 3;
            col = n % 3;
            curpage = n / 20;
            row = row % 10;
            frame = CGRectMake(20, 20, 100, 100);
            frame.origin.x = frame.origin.x + frame.size.width * col + 20 * col + scroll.frame.size.width * curpage;
            frame.origin.y = frame.origin.y + frame.size.height * row + 20 * row;
            NSLog(@"add button col:%d,row:%d,page:%d",col,row,curpage);
            [scroll setContentSize:CGSizeMake(scroll.frame.size.width * (curpage + 1), scroll.frame.size.height)];
            [scroll scrollRectToVisible:CGRectMake(scroll.frame.size.width * curpage, scroll.frame.origin.y, scroll.frame.size.width, scroll.frame.size.height) animated:NO];
            [UIView animateWithDuration:0.2f animations:^{
                [addbutton setFrame:frame];
            }];
            addbutton.index += 1;
        }
        
        
        
            
        }
        
                
        
    }
}
//通过第三页传来的城市名字进行解析数据
- (void)addHandle
{
//
#pragma mark - 小圆圈
    
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    view.backgroundColor = [UIColor blackColor];
//    view.alpha = 0.5;
//    [self.view addSubview:view];
//    [view release];
//
//    self.acticity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32 * OffWidth, 32 * OffHeight)];
//    self.acticity.center = view.center;
//    self.acticity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
//    [view addSubview:self.acticity];
//    [self.acticity startAnimating];
//    [_acticity release];
//    



    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString * name = [self.cityName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [dic setValue:self.cityId forKey:@"city"];
    [dic setValue:name forKey:@"cityName"];
    [dic setValue:@"210" forKey:@"act"];
    [dic setValue:@"0" forKey:@"isfamily"];
    [dic setValue:@"4" forKey:@"mt"];
    [dic setValue:@"3.11.1" forKey:@"sv"];
    [dic setValue:@"4.4.4" forKey:@"osv"];
    [dic setValue:@"868033019886185" forKey:@"imei"];
    [dic setValue:@"M040" forKey:@"dm"];
    [dic setValue:@"10" forKey:@"nt"];
    [dic setValue:@"401FFD8CECB45C1FB7D40679012FC227%7C581688910330868" forKey:@"CUID"];
    [dic setValue:@"115" forKey:@"pid"];
    [dic setValue:@"1009967d" forKey:@"chl"];
    [URL conectionWithUrl:@"http://tq.91.com/api/" dic:dic block:^(NSData *data) {
      
        self.dataArr  = [[NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil] objectForKey:@"items"];
        [self.collect reloadData];
        
//        [self.acticity stopAnimating];
//        [view removeFromSuperview];
//        
    }];



}


- (void)addCollectionView
{
    AddCityLayout *flow = [[AddCityLayout alloc]init];
    flow.itemSize = CGSizeMake(((self.view.frame.size.width - 20 * OffWidth) / 3 ),160 * OffHeight);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    

    self.collect = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flow];
    self.collect.delegate =self;
    self.collect.dataSource = self;
    self.collect.showsVerticalScrollIndicator = NO;
    [self.collect registerClass:[AddCityCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.view addSubview:_collect];
    

    UIImageView *imageV = [[UIImageView alloc]init];
    [imageV sd_setImageWithURL:self.backUrl placeholderImage:[UIImage imageNamed:@"44.png"]];
    [self.collect setBackgroundView:imageV];
 
  
    
    UIBlurEffect *ef = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effV = [[UIVisualEffectView alloc]initWithEffect:ef];
    effV.alpha = 0.9;
    effV.frame = [UIScreen mainScreen].bounds;
    [imageV addSubview:effV];

    
    [flow release];
    [_collect release];
    

        
    }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    AddCityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.layer.cornerRadius = 3;
    cell.backgroundColor =  [[UIColor blackColor] colorWithAlphaComponent:0.5];
    self.items = indexPath.item;
   
    
//    
////    [cell addSubview:_hint];
//    
//     //****************从数据库中读取
//    if (indexPath.item  < self.reciveArr.count) {
//        
//        NovelModel *model = [self.reciveArr objectAtIndex:indexPath.item];
//        
//        cell.high.text = model.high;
//        cell.low.text = model.low;
//        cell.cityName.text = model.cityName;
//        cell.sky.text = model.sky;
//        
//        a =  0;
//        
//      
//        if (indexPath.item == 0) {
//            self.defultLable.frame = CGRectMake(0, cell.contentView.frame.size.height - 20 * OffHeight, cell.contentView.frame.size.width, 20 * OffHeight);
//            self.defultLable.backgroundColor = [UIColor greenColor];
//            self.defultLable.layer.cornerRadius = 2;
//            self.defultLable.layer.masksToBounds = YES;
//            self.defultLable.text = @"默认";
//            self.defultLable.textColor = [UIColor whiteColor];
//            self.defultLable.font = [UIFont boldSystemFontOfSize:15 * OffWidth];
//            self.defultLable.textAlignment = 1;
//            [cell addSubview:_defultLable];
//        }
//        
//        
//        
//  
//    }else{
//    
//    
//        //****************  解析
//        for ( int i = 0; i < self.dataArr.count; i ++) {
//            if ([[[[self.dataArr objectAtIndex:i] objectForKey:@"type"] stringValue] isEqualToString:@"200" ]) {
//                
//                self.dataDic = [[self.dataArr objectAtIndex:i] objectForKey:@"future"];
//                
//            }
//        }
//
//        
//        
//       
//        cell.cityName.text = self.cityName;
//        cell.high.text = [[[self.dataDic objectForKey:@"temp"] objectForKey:@"height"]stringValue];
//        cell.low.text = [[[self.dataDic objectForKey:@"temp"] objectForKey:@"low"]stringValue];
//        cell.sky.text =  [[[[self.dataDic objectForKey:@"items"] objectAtIndex:1] objectForKey:@"climate"] objectForKey:@"name"];
//
//        
//        //将各个城市今天的天气状况信息插入数据库
//
//        NovelModel *model1 = [[NovelModel alloc]init];
//        
//        model1.cityId = self.cityId;
//        model1.cityName = self.cityName;
//        model1.backImage = self.backImage;
//        model1.high = cell.high.text;
//        model1.low =  cell.low.text;
//        model1.sky =  cell.sky.text;
//        [NovelDataBase insertWithModel:model1];
//
//
//        
//     }
//    
//    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(xiaoshi:)];
//    cell.tag = indexPath.item;
//    
//    [cell addGestureRecognizer:press];
//    [press release];
//    
//
//    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    return cell;
    
}



//本页collectionCell的返回值 由第三页的点击次数决定


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
//    return  self.reciveArr.count  + a;
    return 0;
   
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSArray *aaa = self.tabBarController.viewControllers;
    UINavigationController *navi = (UINavigationController *)[aaa firstObject];
    WeatherViewController *wea = (WeatherViewController *)[navi.viewControllers firstObject];
    NSInteger ii = indexPath.item;
    wea.item = ii;
    
    self.tabBarController.selectedIndex = 0;
    [self.navigationController popToRootViewControllerAnimated:YES];
    

}


//添加模拟navigationbar功能的view
- (void)addHeaderView
{
    
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60 * OffHeight)];
//    self.headerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    [self.view addSubview:_headerView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 35 * OffWidth, 15 * OffHeight, 100 * OffWidth, 50 * OffHeight)];
    lable.text = @"城市管理";
    lable.font = [UIFont systemFontOfSize:17 * OffWidth];
    lable.textColor = [UIColor whiteColor];
    [self.view addSubview:lable];
    
    
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeSystem];
    [buttonBack setTitle:@"返回" forState:UIControlStateNormal];
    [buttonBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];    
    buttonBack.frame = CGRectMake(0, 15 * OffWidth, 50 * OffWidth, 50 * OffHeight );
    [buttonBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBack];
    
    UIButton *add = [UIButton buttonWithType:UIButtonTypeSystem];
    add.frame = CGRectMake(self.view.frame.size.width - 50 * OffWidth, 15 * OffHeight, 50 * OffWidth, 50 * OffHeight);
    [add setTitle:@"添加" forState:UIControlStateNormal];
    [add setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [add addTarget:self action:@selector(AddClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:add];
    

   
    
    
}
/*****************第三页往第二页传值(城市名字, cell数量)**********************/



- (void)sendNameMessage:(NSString *)cityName backImage:(NSString *)backImage cityId:(NSString *)cityId
{
    
    
    
    NSLog(@"1fdsfdasfafdsfdsfdsafdsfdsafdsafds");
    self.cityName = cityName;
    self.backImage = backImage;
    self.cityId = cityId;
    self.reciveArr = [NovelDataBase selectAll];
    a = 1;
     [self addHandle];
    [self ggg];
   

    
 

}

/*********************本页 back 按钮 回到第一页   *******************************/
- (void)back:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];;

    
}
/*********************添加撤城市按钮********************************/

- (void)AddClick:(UIButton *)button
{
    self.reciveArr = [NovelDataBase selectAll];

//    
//    if ( [URL judgeConnection]== NO ) {
//        
//        UIAlertView *message = [[UIAlertView alloc]initWithTitle:@"当前无网络,无法进行设置" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [message show];
//        [message release];
//    }else if ( self.reciveArr.count >= 12){
//    
//    
//        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 80 * OffWidth, 400 * OffHeight, 180 * OffWidth, 40 * OffHeight)];
//        view.backgroundColor = [UIColor blackColor];
//        view.layer.cornerRadius = 20;
//        [self.view addSubview:view];
//        [view release];
//        
//        
//        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(15 * OffWidth, 0,150 * OffWidth, 40 * OffHeight)];
//        lable.text = @"最多添加12个城市";
//        lable.textAlignment = 1;
//        lable.font = [UIFont boldSystemFontOfSize:15 * OffWidth];
//        lable.textColor = [UIColor whiteColor];
//        [view addSubview:lable];
//        [lable release];
//        
//        
//        [UIView animateWithDuration:2 animations:^{
//            view.alpha = 0.1;
//            
//        } completion:^(BOOL finished) {
//            [view removeFromSuperview];
//            
//        }];
//
//        
//        
//       }else{
        ChoseViewController *choose = [[ChoseViewController alloc]init];
        choose.delegata = self;
    
        [self presentViewController:choose animated:YES completion:nil];
        [choose release];

//    }
}

- (void)xiaoshi:(UILongPressGestureRecognizer *)press
{
    
  
    if (press.state == UIGestureRecognizerStateEnded) {
        
        return;
        
    } else if (press.state == UIGestureRecognizerStateBegan) {
        
        if (self.reciveArr.count > 1) {

            self.reciveArr = [NovelDataBase selectAll];

            self.items = press.view.tag;
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"是否删除" message:nil  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"是", nil];
         
            
        [alert show];
        [alert release];
        }else{
            
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 80 * OffWidth, 400 * OffHeight, 180 * OffWidth, 40 * OffHeight)];
            view.backgroundColor = [UIColor blackColor];
            view.layer.cornerRadius = 20;
            [self.view addSubview:view];
            [view release];
            
            
            UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(15 * OffWidth, 0,150 * OffWidth, 40 * OffHeight)];
            lable.text = @"最少保留一个城市";
            lable.textAlignment = 1;
            lable.font = [UIFont boldSystemFontOfSize:15 * OffWidth];
            lable.textColor = [UIColor whiteColor];
            [view addSubview:lable];
            [lable release];
            
            
            [UIView animateWithDuration:2 animations:^{
                view.alpha = 0.1;
                
            } completion:^(BOOL finished) {
                [view removeFromSuperview];
                
            }];
            
            
        }
    }
    

    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
       
    }else{

        
        NovelModel *model = [[NovelModel alloc]init];
        model =  [self.reciveArr objectAtIndex:self.items];
      
        [NovelDataBase deleteWithModel:model];
        
        self.reciveArr = [NovelDataBase selectAll];
        [self.headerView removeFromSuperview];
        [self.collect removeFromSuperview];
        [self addCollectionView];
        [self addHeaderView];
        
        [model release];
        
    }
    
}



















- (void)viewDidUnload
{
    [self setBackground:nil];
    [self setScroll:nil];
    addbutton = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark-- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGRect frame = self.background.frame;
    
    frame.origin.x = preFrame.origin.x + (preX - scrollView.contentOffset.x)/10 ;
    
    
    if (frame.origin.x <= 0 && frame.origin.x > scrollView.frame.size.width - frame.size.width ) {
        self.background.frame = frame;
    }
    NSLog(@"offset:%f",(scrollView.contentOffset.x - preX));
    NSLog(@"origin.x:%f",frame.origin.x);
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    preX = scrollView.contentOffset.x;
    preFrame = background.frame;
    NSLog(@"prex:%f",preX);
}
- (void)Addbutton
{
    
    ChoseViewController *choose = [[ChoseViewController alloc]init];
    choose.delegata = self;

    [self presentViewController:choose animated:YES completion:nil];
}
#pragma mark-- BJGridItemDelegate
- (void)gridItemDidClicked:(BJGridItem *)gridItem{
    NSLog(@"grid at index %d did clicked",gridItem.index);
    if (gridItem.index == [gridItems count]-1) {
        [self Addbutton];
    }
}
- (void)gridItemDidDeleted:(BJGridItem *)gridItem atIndex:(NSInteger)index{
    NSLog(@"grid at index %ld did deleted",gridItem.index);
    BJGridItem * item = [gridItems objectAtIndex:index];
    
    [gridItems removeObjectAtIndex:index];
    [UIView animateWithDuration:0.2 animations:^{
        CGRect lastFrame = item.frame;
        CGRect curFrame;
        
        
        for (int i=index; i < [gridItems count]; i++) {
            BJGridItem *temp = [gridItems objectAtIndex:i];
            curFrame = temp.frame;
            [temp setFrame:lastFrame];
            lastFrame = curFrame;
            [temp setIndex:i];
        }
        [addbutton setFrame:lastFrame];
    }];
    [item removeFromSuperview];
    item = nil;
}
- (void)gridItemDidEnterEditingMode:(BJGridItem *)gridItem{
    NSLog(@"gridItems count:%ld",[gridItems count]);
    for (BJGridItem *item in gridItems) {
        NSLog(@"%ld",item.index);
        [item enableEditing];
    }
    //[addbutton enableEditing];
    isEditing = YES;
    
}
//- (void)gridItemDidMoved:(BJGridItem *)gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer *)recognizer{
//    CGRect frame = gridItem.frame;
//    CGPoint _point = [recognizer locationInView:self.scroll];
//    CGPoint pointInView = [recognizer locationInView:self.view];
//    frame.origin.x = _point.x - point.x;
//    frame.origin.y = _point.y - point.y;
//    gridItem.frame = frame;
//    NSLog(@"gridItemframe:%f,%f",frame.origin.x,frame.origin.y);
//    NSLog(@"move to point(%f,%f)",point.x,point.y);
//    
//    NSInteger toIndex = [self indexOfLocation:_point];
//    NSInteger fromIndex = gridItem.index;
//    NSLog(@"fromIndex:%d toIndex:%ld",fromIndex,toIndex);
//    
//    if (toIndex != unValidIndex && toIndex != fromIndex) {
//        BJGridItem *moveItem = [gridItems objectAtIndex:toIndex];
//        [scroll sendSubviewToBack:moveItem];
//        [UIView animateWithDuration:0.2 animations:^{
//            CGPoint origin = [self orginPointOfIndex:fromIndex];
//            //NSLog(@"origin:%f,%f",origin.x,origin.y);
//            moveItem.frame = CGRectMake(origin.x, origin.y, moveItem.frame.size.width, moveItem.frame.size.height);
//        }];
//        [self exchangeItem:fromIndex withposition:toIndex];
//        //移动
//        
//    }
//    //翻页
//    if (pointInView.x >= scroll.frame.size.width - threshold) {
//        [scroll scrollRectToVisible:CGRectMake(scroll.contentOffset.x + scroll.frame.size.width, 0, scroll.frame.size.width, scroll.frame.size.height) animated:YES];
//    }else if (pointInView.x < threshold) {
//        [scroll scrollRectToVisible:CGRectMake(scroll.contentOffset.x - scroll.frame.size.width, 0, scroll.frame.size.width, scroll.frame.size.height) animated:YES];
//    }scroll;
//    
//    
//}
- (void) gridItemDidEndMoved:(BJGridItem *) gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer*) recognizer{
    CGPoint _point = [recognizer locationInView:self.scroll];
    NSInteger toIndex = [self indexOfLocation:_point];
    if (toIndex == unValidIndex) {
        toIndex = gridItem.index;
    }
    CGPoint origin = [self orginPointOfIndex:toIndex];
    [UIView animateWithDuration:0.2 animations:^{
        gridItem.frame = CGRectMake(origin.x, origin.y, gridItem.frame.size.width, gridItem.frame.size.height);
    }];
    NSLog(@"gridItem index:%ld",gridItem.index);
}

- (void) handleSingleTap:(UITapGestureRecognizer *) gestureRecognizer{
    if (isEditing) {
        for (BJGridItem *item in gridItems) {
            [item disableEditing];
        }
        [addbutton disableEditing];
    }
    isEditing = NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if(touch.view != scroll){
        return NO;
    }else
        return YES;
}

#pragma mark-- private
- (NSInteger)indexOfLocation:(CGPoint)location{
    NSInteger index;
    NSInteger _page = location.x / 320;
    NSInteger row =  location.y / (gridHight + 20);
    NSInteger col = (location.x - _page * 320) / (gridWith + 20);
    if (row >= rows || col >= columns) {
        return  unValidIndex;
    }
    index = itemsPerPage * _page + row * 2 + col;
    if (index >= [gridItems count]) {
        return  unValidIndex;
    }
    
    return index;
}

- (CGPoint)orginPointOfIndex:(NSInteger)index{
    CGPoint point = CGPointZero;
    if (index > [gridItems count] || index < 0) {
        return point;
    }else{
        NSInteger _page = index / itemsPerPage;
        NSInteger row = (index - _page * itemsPerPage) / columns;
        NSInteger col = (index - _page * itemsPerPage) % columns;
        
        point.x = _page * 320 + col * gridWith + (col +1) * space;
        point.y = row * gridHight + (row + 1) * space;
        return  point;
    }
}

- (void)exchangeItem:(NSInteger)oldIndex withposition:(NSInteger)newIndex{
    ((BJGridItem *)[gridItems objectAtIndex:oldIndex]).index = newIndex;
    ((BJGridItem *)[gridItems objectAtIndex:newIndex]).index = oldIndex;
    [gridItems exchangeObjectAtIndex:oldIndex withObjectAtIndex:newIndex];
}












@end
